import { createStore, Commit } from 'vuex'
import axios from 'axios'

export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
}

export interface ColumnProps {
  _id: string;
  title: string;
  avatar?: ImageProps;
  description: string;
}

export interface PostProps {
  _id?: string;
  title: string;
  excerpt?: string;
  content?: string;
  image?: ImageProps | string;
  createdAt?: string;
  column?: string;
  author?: string;
}
export interface UserProps {
  isLogin: boolean;
  nickName?: string;
  _id?: string;
  column?: string;
  email?: string
}
export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}
export interface GlobalDataProps {
  columns: ColumnProps[];
  posts: PostProps[];
  user: UserProps;
  loading: boolean;
  token: string;
  error: GlobalErrorProps;
}
const getAndCommit = async (url: string, mutationName: string, commit: Commit, data?: any) => {
  const res = await axios.post(url, data)
  commit(mutationName, res.data)
  return res.data
}
const store = createStore<GlobalDataProps>({
  state: {
    columns: [],
    posts: [],
    user: { isLogin: false },
    loading: false,
    token: localStorage.getItem('token') || '',
    error: { status: false }
  },
  getters: {
    getColumnsById: (state) => (id: string) => {
      return state.columns.find(c => c._id === id)
    },
    getPostsByCid: (state) => (id: string) => {
      return state.posts.filter(post => post.column === id).map(item => {
        if (!item.image) {
          item.image = {
            url: require('@/assets/avatar.jpg')
          }
        }
        return item
      })
    }
  },
  mutations: {
    // login (state) {
    //   state.user = { ...state.user, isLogin: true, name: 'setsail' }
    // },
    loginOut (state) {
      localStorage.removeItem('token')
      state.user = { isLogin: false }
      state.token = ''
    },
    setLoading (state, status) {
      state.loading = status
    },
    setError (state, e: GlobalErrorProps) {
      state.error = e
    },
    createPost (state, newPost) {
      state.posts.push(newPost)
    },
    fetchColumns (state, rawData) {
      state.columns = rawData.data.list
    },
    fetchColumn (state, rawData) {
      state.columns = [rawData.data]
    },
    fetchPosts (state, rawData) {
      state.posts = rawData.data.data.list
    },
    login (state, rawData) {
      state.token = rawData.data.token
      localStorage.setItem('token', rawData.data.token)
    },
    fetchCurrentUser (state, rawData) {
      console.log(' rawData', rawData)
      state.user = { ...state.user, isLogin: true, ...rawData.data }
    },
    createPosts () {
      console.log(11)
    }
  },
  actions: {
    async fetchColumns ({ commit }) {
      return getAndCommit('/api/columns', 'fetchColumns', commit)
    },
    async fetchColumn ({ commit }, id) {
      return getAndCommit('/api/columnDetail', 'fetchColumn', commit, { id })
    },
    async fetchPosts ({ commit }, id) {
      return getAndCommit('/api/posts/postsList', 'fetchPosts', commit, { id })
    },
    async login ({ commit }, payload) {
      return getAndCommit('/api/login', 'login', commit, payload)
    },
    async createPosts ({ commit }, payload) {
      return getAndCommit('/api/posts/createposts', 'createPosts', commit, payload)
    },
    async fetchCurrentUser ({ commit }, token) {
      console.log('token', token)
      return getAndCommit('/api/user/current', 'fetchCurrentUser', commit, token)
    },
    async loginAndFetch ({ dispatch }, payload) {
      return dispatch('login', payload).then(res => {
        return dispatch('fetchCurrentUser', { token: localStorage.getItem('token') })
      })
    }
  }
})

export default store
